import { removeToken, setToken, getToken, setTimeStamp } from '@/utils/auth'
import { login, getUserInfo, getUserDateilById } from '@/api/user'
import { resetRouter } from '@/router'
const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  removeToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, result) {
    state.userInfo = result
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login(context, data) {
    const result = await login(data) // 拿到token
    context.commit('setToken', result) // 设置token
    // 登录成功 存时间戳
    setTimeStamp()
  },
  async getUserInfo(context) {
    const result = await getUserInfo()
    // 获取用户头像
    const baseInfo = await getUserDateilById(result.userId)
    const obj = { ...result, ...baseInfo }
    context.commit('setUserInfo', obj)
    return result
  },
  logout(context) { // 登出
    context.commit('removeToken')
    context.commit('removeUserInfo')
    resetRouter()// 重置路由
    context.commit('permission/setRoutes', [], { root: true })
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

